package com.lxw.station.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.lxw.station.core.R;
import com.lxw.station.core.Result;
import com.lxw.station.entity.VideoDto;
import com.lxw.station.entity.VideoVo;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.ArrayList;
import java.util.List;

@RestController
public class VideoController {
    public static void main(String[] args) {
        VideoDto videoDto = new VideoDto();
        videoDto.setKeyword("kafka");
        VideoController controller = new VideoController();
        Result result = controller.videoList(videoDto);
        Object data = result.getData();
        System.out.println("data = " + data);
    }
    private String cookie = "_uuid=9DF4F2F2-47B9-22B6-F59A-A8C10C658393265297infoc; enable_web_push=undefined; header_theme_version=undefined; buvid_fp=0f14aff6726a04789db0ba942ba1317c; buvid3=C4518348-C136-256A-F660-38EA96D4971D49657infoc; b_nut=1708214666; buvid4=1010A954-10E9-D08B-82EF-1278035AD2E749657-024021800-Da1Cmh2s4TKHhBvxWnSrMg%3D%3D; CURRENT_FNVAL=4048; rpdid=|(kYl|~u)R)J0J'u~|)kuRY~Y; PVID=1; DedeUserID=702211544; DedeUserID__ckMd5=165187cda1b9f075; CURRENT_QUALITY=80; FEED_LIVE_VERSION=undefined; bili_ticket=eyJhbGciOiJIUzI1NiIsImtpZCI6InMwMyIsInR5cCI6IkpXVCJ9.eyJleHAiOjE3MTAzNzQxMjcsImlhdCI6MTcxMDExNDg2NywicGx0IjotMX0.YzPhgcDhiKBMZCQmvf9r_6shc7teaF2F6r4ZFgk4g9w; bili_ticket_expires=1710374067; SESSDATA=bc98694a%2C1725666928%2Cce14a%2A31CjCxI-6GYnUODm_8y4XiweKv272zq5odBHxEmsuMnRW9nTgEThHMdZmEZM-mZvcQowoSVlE2ZWItWmROUGtVcXFTZkVlYmhmdDdnbTktZF9scVZpb3c1UzNJNXlsZGZvN3U0cWtGYS1FSXU4N0VZN041UkJYWEhJNDJKQktFTzVBZTBXSEw0WERRIIEC; bili_jct=a23627e4e9d952ba26cfcc0209ce39e0; sid=7yv3ysp0; bp_video_offset_702211544=907118997271478357; home_feed_column=4; b_lsid=BF6A57A2_18E312A1978; browser_resolution=1275-1279";
    private RestTemplate restTemplate = new RestTemplate();
    @PostMapping("/videoList")
    public Result videoList(@RequestBody VideoDto videoDto) {
        String keyword = videoDto.getKeyword();
        if (!StringUtils.hasText(keyword)) {
            return R.error(500,"keyword 不能为空");
        }
        String cookie = videoDto.getCookie();
        if (!StringUtils.hasText(cookie)) {
            cookie = this.cookie;
        }
        String url = "https://api.bilibili.com/x/web-interface/wbi/search/all/v2?__refresh__=true&_extra=&context=&page=1&page_size=42&order=&duration=&from_source=&from_spmid=333.337&platform=pc&highlight=1&single_column=0&qv_id=f2n7O2fSac731PnjjNFHUAGTYrY8wN84&ad_resource=5646&source_tag=3&web_location=1430654&w_rid=8b093eac9dbe20f09fb6b7bf3a51a743&wts=1710225740&keyword=" + keyword;
        HttpHeaders headers = new HttpHeaders();
        headers.add("Cookie", cookie);
        headers.add("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/122.0.0.0 Safari/537.36");
        HttpEntity<Object> entity = new HttpEntity<>(null, headers);
        ResponseEntity<String> exchange = restTemplate.exchange(url, HttpMethod.GET, entity, String.class);
        String body = exchange.getBody();
        JSONArray results = JSON.parseObject(body).getJSONObject("data").getJSONArray("result");
        List<VideoVo> list = new ArrayList<>();
        for (int i = 0; i < results.size(); i++) {
            JSONObject result = results.getJSONObject(i);
            if ("video".equals(result.getString("result_type"))) {
                JSONArray array = result.getJSONArray("data");
                for (int j = 0; j < array.size(); j++) {
                    JSONObject object = array.getJSONObject(j);
                    String id = object.getString("id");
                    String title = object.getString("title").replace("<em class=\"keyword\">", "").replace("</em>", "");
                    System.out.println(id + "\t" + title);
                    VideoVo videoVo = new VideoVo();
                    videoVo.setId(id);
                    videoVo.setTitle(title);
                    list.add(videoVo);
                }
            }
        }
        return R.ok(list);
    }
    @GetMapping("/videoDetails/{id}")
    public Result<String> videoDetails(@PathVariable String id) {
        String url = "https://api.bilibili.com/x/web-interface/wbi/view/detail?aid=" + id;
        HttpHeaders headers = new HttpHeaders();
        headers.add("Cookie", cookie);
        headers.add("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.5735.289 Safari/537.36");
        HttpEntity<Object> entity = new HttpEntity<>(null, headers);
        ResponseEntity<String> exchange = restTemplate.exchange(url, HttpMethod.GET, entity, String.class);
        String body = exchange.getBody();
        System.out.println("body = " + body);
        JSONArray jsonArray = JSON.parseObject(body).getJSONObject("data").getJSONObject("View").getJSONArray("pages");
        StringBuilder builder = new StringBuilder();
        for (int i = 0; i < jsonArray.size(); i++) {
            String title = jsonArray.getJSONObject(i).getString("part");
            System.out.println(title);
            builder.append(title).append("\n");
        }
        return R.ok(builder.toString());
    }
}
